import { reqGetAddressList, reqDelAddress } from '@/api/address'
import { swipeCellBehavior } from '@/behaviors/swipeCell'

const app = getApp()
Page({
  behaviors: [swipeCellBehavior],
  // 页面的初始数据
  data: {
    addressList: [],
    showEmptyState: false, //先渲染列表
    isIos: false
  },

  onLoad: function (options) {
    const { flag, id } = options
    // flag为1表示从订单详情页进入的
    if (flag == 1) {
      this.setData({
        highLightItemId: id,
        flag: true
      })
    }
  },
  // 生命周期函数--监听页面加载
  onShow: function (options) {
    this.getAddressData()
    this.setData({
      isIos: app.globalData.isIos
    })
  },

  async getAddressData() {
    const res = await reqGetAddressList()
    if (res.code == 200) {
      if (res.data.length === 0) {
        this.setData({
          showEmptyState: true,
          addressList: []
        })
        return
      }
      this.setData({
        addressList: res.data,
        showEmptyState: false
      })
    }
  },

  // 删除
  async delAddress(e) {
    const { id } = e.currentTarget.dataset
    // 删除确认
    const delConfirm = await wx.modal({ content: '确定删除该地址吗？' })
    if (delConfirm) {
      const res = await reqDelAddress(id)
      if (res.code == 200) {
        wx.toast({ title: '删除成功' })
        this.getAddressData()
      } else {
        wx.toast({ title: '删除失败，请重试' })
      }
    }
  },

  goEditAddress(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/modules/settingsModule/pages/address/add-address/add-address?id=${id}`
    })
  },

  goAddAddress() {
    wx.navigateTo({
      url: '/modules/settingsModule/pages/address/add-address/add-address'
    })
  },

  // 更改订单收货地址
  changeOrderAddress(e) {
    // 若是从订单详情进入才往下操作
    if (!this.data.flag) return
    const { id } = e.currentTarget.dataset
    // 找到对应项并传递给订单详情页
    const orderAddress = this.data.addressList.find((item) => item.id === id)
    if (!orderAddress) {
      wx.toast({ title: '该地址不存在' })
      return
    }
    // 方式一：用navigateTo，加eventChannel传参，但这种方式会报达到跳转上限错
    // wx.navigateTo({
    //   url: '/modules/orderModule/pages/order/order-detail/order-detail?reFlag=1',
    //   success: function (res) {
    //     res.eventChannel.emit('updateOrderAddress', orderAddress)
    //   }
    // })
    // 方式二：用wx.navigateBack，加getCurrentPages获取页面栈
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2]
    wx.navigateBack({
      delta: 1,
      success: () => {
        prevPage.setData({
          newOrderAddress: orderAddress
        })
      }
    })
  }
})
